(function () {

  var global = window;
  var wrapExec = {};

  seajs.on("resolve", function (data) {

    var id = data.id
    if (!id) return ""


    var m = id.match(/[^?]+?(\.\w+)?(\?.*)?$/);

    //白名单
    var WhiteListReg = /\.(tpl|html|json|css)/i;  //同时解决跨域问题

    if (m && (!WhiteListReg.test(m[1]) || !m[1])) {
      var uri = seajs.resolve(id, data.refUri);//解析出最终url
      var query = m[2] || '';
      //字典式回调
      wrapExec[uri] = function (uri, content) {
        var wrappedContent;
        var CMD_REG = /define\(.*function\s*\(\s*require\s*(.*)?\)\s*\{/;  //含就行 不一定以 define开头
        if (CMD_REG.test(content) ||
          query.indexOf('nowrap') > 0) {  //可以直接指定不让含
          wrappedContent = content;
        } else {
          wrappedContent = 'define(function(require, exports, module) {\n' +
            content + '\n})';
        }
        wrappedContent = wrappedContent + '//# sourceURL=' + uri;
        globalEval(wrappedContent, uri); //解析
      }
      data.uri = uri
    }

  })

  seajs.cssList = [];

  //发送前执行
  seajs.on("request", function (data) {
    var exec = wrapExec[data.uri]

    if (exec) {
      xhr(data.requestUri, function (content) {
        if (data.requestUri.indexOf('.css') > -1) {
          seajs.cssList.push({
            key: data.requestUri,
            content: content
          });
          console.log(data.requestUri);
        }
        exec(data.uri, content)
        data.onRequest()
      })

      data.requested = true; //直接标记为完成
    }
  })


  // 异步
  function xhr(url, callback) {
    var r = global.ActiveXObject ?
      new global.ActiveXObject("Microsoft.XMLHTTP") :
      new global.XMLHttpRequest()

    r.open("GET", url, true);//get请求

    r.onreadystatechange = function () {
      if (r.readyState === 4) {
        callback(r.responseText)
      }
    }
    return r.send(null)
  }

  //解析一下
  function globalEval(content, uri) {
    if (content && /\S/.test(content)) {
      (global.execScript || function (content) {
        try {
          (global.eval || eval).call(global, content)
        } catch (ex) {
          ex.fileName = uri;
          console.error(ex);
        }
      })(content)
    }
  }

  define("seajs-wrap-debug", [], {});
})();